package com.social.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.view.MiniAbstractExcelView;
import com.alibaba.fastjson.JSON;
import com.social.pojo.NewCaseManagementForm;
import com.social.pojo.RegistrationOfCases;
import com.social.pojo.Ultimate;
import com.social.service.NewCaseManagementFormService;
import com.social.service.UltimateService;
import com.social.util.JsonUtil;
import com.social.util.PageUtil;
import com.social.util.StatusUtil;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 科长审核管理
 */
@Controller
@RequestMapping("ultimate")
public class UltimateController {
    /**
     * Ultimate 业务层
     */
    @Autowired
    private UltimateService ultimateService;
    /**
     * NewCaseManagementForm 业务层
     */
    @Autowired
    private NewCaseManagementFormService newCaseManagementForm;

    /**
     * 分页查询所有
     *
     * @param typeStatus     类型状态
     * @param approvalStatus 审批状态
     * @param page           当前页数
     * @param pageNum        每页条数
     * @param session        作用域
     * @param status         状态
     * @return controller 或 页面
     */
    @RequestMapping("selectByPage")
    public String select(Integer typeStatus, Integer approvalStatus, Integer page, Integer pageNum, HttpSession session, Integer status) {
        //状态方法
        Map<String, Integer> mapStatus = StatusUtil.status(typeStatus, approvalStatus);
        //获取状态
        Integer status1 = mapStatus.get("typeStatus");
        Integer status2 = mapStatus.get("approvalStatus");
        //所有条数
        Integer count = ultimateService.ultimateSelectCount(null, null, null, status1, status2);
        //分页方法
        Map<String, Integer> util = PageUtil.page(pageNum, page, count);
        Integer pages = util.get("page");
        Integer num = util.get("pageNum");
        Integer remaining_pages = util.get("remaining_pages");
        Integer counts = util.get("count");
        //分页数据
        List<RegistrationOfCases> registrationOfCases = ultimateService.ultimateSelectPage(status1, status2, pages, num);
        Map<String, Object> map = new HashMap<String, Object>();
        //存入分页数据
        map.put("num", remaining_pages);
        map.put("page", pages);
        map.put("count", counts);
        //存入map集合
        session.setAttribute("map", map);
        //存入分页后的数据
        session.setAttribute("data", registrationOfCases);
        if (status == 7) {
            return "redirect:/AuditNcmFormController/selectAll?status=" + status;
        } else if (status == 10) {
            return "redirect:/PendingBankCases/selectAll?status=" + status;
        } else {
            return StatusUtil.statusYe(status);
        }
    }

    /**
     * 分页模糊查询
     *
     * @param unitName           单位名称
     * @param organizationalCode 组织机构代码
     * @param nameOfRegistrant   登记人姓名
     * @param page               当前页
     * @param pageNum            每页条数
     * @param session            作用域
     * @param status             跳转页面状态
     * @param typeStatus         类型状态
     * @param approvalStatus     审批状态
     * @return 页面
     */
    @RequestMapping("selectByLike")
    public String caseRegistrationLike(String unitName, String organizationalCode, String nameOfRegistrant, Integer page, Integer pageNum, HttpSession session, Integer status, Integer typeStatus, Integer approvalStatus) {
        //状态方法
        Map<String, Integer> likeStatus = StatusUtil.status(typeStatus, approvalStatus);
        //获取状态
        Integer status1 = likeStatus.get("typeStatus");
        Integer status2 = likeStatus.get("approvalStatus");
        //所有条数
        Integer count = ultimateService.ultimateSelectCount("%" + unitName + "%", "%" + nameOfRegistrant + "%", "%" + organizationalCode + "%", status1, status2);
        //分页方法
        Map<String, Integer> util = PageUtil.page(pageNum, page, count);
        Integer pages = util.get("page");
        Integer num = util.get("pageNum");
        Integer remaining_pages = util.get("remaining_pages");
        Integer counts = util.get("count");
        //分页数据
        List<RegistrationOfCases> registrationOfCasess = ultimateService.ultimateSelectLike("%" + unitName + "%", "%" + nameOfRegistrant + "%", "%" + organizationalCode + "%", status1, status2, pages, num);
        //模糊查询
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nums", remaining_pages);
        map.put("pages", pages);
        map.put("counts", counts);
        //存入map集合
        session.setAttribute("map", map);
        //存入分页数据
        session.setAttribute("data", registrationOfCasess);
        //存入前台请求的模糊查询字段（分页使用）
        session.setAttribute("unitName", unitName);
        session.setAttribute("organizationalCode", organizationalCode);
        session.setAttribute("nameOfRegistrant", nameOfRegistrant);
        //根据状态返回页面
        return StatusUtil.statusYe(status);
    }

    /**
     * 根据 ultimate primary key查询
     *
     * @param id ultimate primary key
     * @return 查询的数据
     */
    @RequestMapping(value = "selectById", produces = "text/application;charset=utf-8")
    @ResponseBody
    public String selectById(Integer id) {
        Ultimate ultimate = ultimateService.selectByPrimaryKey(id);
        return JSON.toJSONString(ultimate);
    }

    /**
     * 科长审核通过与不通过
     *
     * @param approvalStatus 审批状态
     * @param typeStatus     类型状态
     * @param id             ultimate primary key
     * @param session        作用域
     * @return ultimate primary key
     */

    @RequestMapping("updateStatus")
    @ResponseBody
    public String updateStatus(Integer approvalStatus, Integer typeStatus, Integer id, HttpSession session) {
        if (approvalStatus == 1) {
            //审核通过
            ultimateService.updateStatus(approvalStatus, typeStatus, id);
            NewCaseManagementForm newCaseManagementForm = new NewCaseManagementForm();
            Integer state = (Integer) session.getAttribute("state");
            newCaseManagementForm.setRegistrationOfCasesId(id);
            if (newCaseManagementForm.getState() == null) newCaseManagementForm.setState(0);
            newCaseManagementForm.setState(state);
            this.newCaseManagementForm.insertSelective(newCaseManagementForm);
        } else if (approvalStatus == 2) {
            //审核不通过
            ultimateService.updateStatus(approvalStatus, typeStatus, id);
        }
        return JSON.toJSONString(id);
    }


    /**
     * 修改数据
     *
     * @param ultimate 实体类
     * @return 状态
     */
    @RequestMapping("update")
    @ResponseBody
    public String update(Ultimate ultimate) {
        int status = ultimateService.updateByPrimaryKeySelective(ultimate);
        JsonUtil jsonUtil = new JsonUtil();
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        return JSON.toJSONString(restates);
    }

    /**
     * 批量删除
     *
     * @param id     ultimate primary key
     * @param status 状态
     * @return controller
     */
    @RequestMapping("bulkDelete")
    public String bulkDelete(String id, Integer status) {
        List<Integer> list = new ArrayList<>();
        String[] strs = id.split(",");
        for (int i = 0; i < strs.length; i++) {
            list.add(Integer.parseInt(strs[i]));
            ultimateService.bulkDelete(list);
        }
        return StatusUtil.statusController(status);
    }

    /**
     * 批量导出
     *
     * @param map 集合
     * @param id  ultimate primary key
     * @return controller
     */
    @RequestMapping("bulkExport")
    //@ResponseBody
    public String bulkExport(ModelMap map, String id) {
        String[] strs = id.split(",");
        ArrayList<Ultimate> ultimates = new ArrayList<>();
        for (int i = 0; i < strs.length; i++) {
            Integer[] ids = new Integer[]{Integer.valueOf(strs[i])};
            List<Ultimate> ultimates2 = ultimateService.bulkExport(ids);
            ultimates.addAll(ultimates2);
        }
        ExportParams exportParams = new ExportParams("管理", "所有数据", ExcelType.XSSF);
        //导出的集合
        map.put(NormalExcelConstants.DATA_LIST, ultimates);
        map.put(NormalExcelConstants.CLASS, Ultimate.class);
        map.put(NormalExcelConstants.PARAMS, exportParams);
        map.put(NormalExcelConstants.FILE_NAME, "科长导出的数据");
        return "easypoiExcelView";
    }

    /**
     * 批量导入
     *
     * @param file    导入文件
     * @param session 作用域
     * @return 删除或修改状态
     * @throws Exception 文件找不到
     */
    @RequestMapping(value = "bulkImport", produces = "text/application;charset=utf-8")
    @ResponseBody
    public String bulkImport(MultipartFile file, HttpSession session) throws Exception {
        //状态
        int status = 0;
        try {
            //获取后缀名
            String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File files = new File(session.getServletContext().getRealPath("/importFile/"));
            //判断文件夹是否存在
            if (!files.exists()) {
                files.mkdirs();
            }
            //随机数
            double v = Math.random() * 100;
            //时间戳
            String yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH").format(new Date());
            //设置文件上传路径并将文件名设置进去
            file.transferTo(new File(files, (int) v + yyyyMMddHH + fileName));
            //创建导入对象
            ImportParams params = new ImportParams();
            params.setTitleRows(1); //表格标题行数,默认0
            params.setHeadRows(1);  //表头行数,默认1

            //获取导入数据
            List<Ultimate> teachers = ExcelImportUtil.importExcel(new FileInputStream(new File(files + "/" + (int) v + yyyyMMddHH + fileName)), Ultimate.class, params);
            for (Ultimate teacher : teachers) {
                Ultimate ultimate = ultimateService.selectByPrimaryKey(teacher.getId());
                if (ultimate == null) {
                    status = ultimateService.insertSelective(teacher);
                } else {
                    status = ultimateService.updateByPrimaryKeySelective(teacher);
                }
            }
        } catch (Exception e) {
            JsonUtil jsonUtil = new JsonUtil();
            jsonUtil.setCode("请选择正确的文件");
            return JSON.toJSONString(jsonUtil.getCode());
        }
        JsonUtil jsonUtil = new JsonUtil();
        //设置状态
        Boolean restates = jsonUtil.getRestates(status);
        return JSON.toJSONString(restates);
    }
}
